package com.tuniu.agents.tools.flights.utils;

import com.tuniu.agents.tools.flights.model.ApproachCity;
import com.tuniu.agents.tools.flights.model.ApproachCityResponse;
import com.tuniu.agents.util.HttpManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AirportQueryUtils {
    private static final Logger logger = LoggerFactory.getLogger(AirportQueryUtils.class);

    /**
     * Batch query city airport information
     * @param httpManager HTTP manager
     * @param apiUrl API endpoint
     * @param cities List of cities to query
     * @return A map containing the airport status of each city
     */
    public static Map<String, Boolean> batchCheckAirports(HttpManager httpManager, String apiUrl, List<String> cities) {
        ApproachCity request = buildRequest(cities);
        ApproachCityResponse response = executeAirportQuery(httpManager, apiUrl, request);
        return processResponse(response, cities);
    }

    private static ApproachCity buildRequest(List<String> cities) {
        ApproachCity request = new ApproachCity();
        request.setCity(new ArrayList<>(cities));
        return request;
    }

    private static ApproachCityResponse executeAirportQuery(HttpManager httpManager, String apiUrl, ApproachCity request) {
        try {
            return httpManager.post(apiUrl, request, ApproachCityResponse.class);
        } catch (Exception e) {
            logger.error("Airport query interface exception", e);
        }
        return new ApproachCityResponse();
    }

    private static Map<String, Boolean> processResponse(ApproachCityResponse response, List<String> cities) {
        Map<String, Boolean> result = new HashMap<>();
        for (String city : cities) {
            result.put(city, hasValidAirport(response, city));
        }
        return result;
    }

    private static boolean hasValidAirport(ApproachCityResponse response, String city) {
        if (response.getData() == null) {
            return false;
        }
        List<ApproachCityResponse.CityAirPort> airports = response.getData().get(city);
        if (airports == null) return false;

        return airports.stream().anyMatch(airport ->
                airport.isHave() ||
                        !StringUtils.hasText(airport.getLocationAirport())
        );
    }
}